package com.baidu.springcloud.lb.impl;

import com.baidu.springcloud.lb.LoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ShiLei
 * @version v1.0
 * @date 2020-03-16 20:30
 */
@Component
public class LoadBalancerImpl implements LoadBalancer {

    /**
     * 原子整型类
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 利用CAS比较并交换 与 自旋锁来实现负载均衡
     * CAS 比较并交换  比较当前值是否与修改值相等 如果返回true 取反跳出循环
     * @return 返回第几次访问请求
     */
    public final int getAndIncrement() {
        int current;
        int next;
        do {
            current = atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("next: " + next);
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {

        int index = getAndIncrement() % serviceInstances.size();

        return serviceInstances.get(index);
    }
}
